<?php

namespace backend\controllers;

use Yii;
use backend\models\Taozhuang;
use backend\models\TaozhuangSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use \yii\web\Response;
use yii\helpers\Html;

use backend\models\Image;
use backend\models\UploadForm;
use backend\models\GrpSpace;
use backend\models\BuildType;
use backend\models\TaozhuangPos;
use yii\web\ForbiddenHttpException;

/**
 * TaozhuangController implements the CRUD actions for Taozhuang model.
 */
class TaozhuangController extends Controller
{
	const BASE_URL = '/furniture_test/furniture_test.php?';
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                    'bulk-delete' => ['post'],
                ],
            ],
        ];
    }
	public function beforeAction($action)
    {
    	//如果未登录，则直接跳转
    	if(Yii::$app->user->isGuest){
    		return $this->redirect(['/site/login']);
    	}
    
    
    	$action = Yii::$app->controller->action->id;
    	$controller = Yii::$app->controller->id;
    	if(\Yii::$app->user->can('taozhuang') || \Yii::$app->user->can('taozhuang-manage')){
    		return true;
    	}else{
    		throw new ForbiddenHttpException(Yii::t('app','Sorry , You don\'t have permission'));
    	}
    }
    /**
     * Lists all Taozhuang models.
     * @return mixed
     */
    public function actionIndex()
    {    
        $searchModel = new TaozhuangSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }


    /**
     * Displays a single Taozhuang model.
     * @param integer $id
     * @return mixed
     */
     public function actionView($id)
    {   
        $request = Yii::$app->request;
        if($request->isAjax){
            Yii::$app->response->format = Response::FORMAT_JSON;
            return [
                    'title'=> Yii::t('app', 'Taozhuang'),
                    'content'=>$this->renderPartial('view', [
                        'model' => $this->findModel($id),
                    ]),
                    'footer'=> Html::button('Close',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"])/*.
                            Html::a('Edit',['update','id'=>$id],['class'=>'btn btn-primary','role'=>'modal-remote'])*/
                ];    
        }else{
            return $this->render('view', [
                'model' => $this->findModel($id),
            ]);
        }
    }


    /**
     * Creates a new Taozhuang model.
     * For ajax request will return json object
     * and for non-ajax request if creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $request = Yii::$app->request;
        $model = new Taozhuang();  

        if($request->isAjax){
            /*
            *   Process for ajax request
            */
            Yii::$app->response->format = Response::FORMAT_JSON;
            if($request->isGet){
                return [
                    'title'=> "Create new Taozhuang",
                    'content'=>$this->renderPartial('create', [
                        'model' => $model,
                    ]),
                    'footer'=> Html::button('Close',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"]).
                                Html::button('Save',['class'=>'btn btn-primary','type'=>"submit"])
        
                ];         
            }else if($model->load($request->post()) && $model->save()){
                return [
                    'forceReload'=>'true',
                    'title'=> "Create new Taozhuang",
                    'content'=>'<span class="text-success">Create Taozhuang success</span>',
                    'footer'=> Html::button('Close',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"]).
                            Html::a('Create More',['create'],['class'=>'btn btn-primary','role'=>'modal-remote'])
        
                ];         
            }else{           
                return [
                    'title'=> "Create new Taozhuang",
                    'content'=>$this->renderPartial('create', [
                        'model' => $model,
                    ]),
                    'footer'=> Html::button('Close',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"]).
                                Html::button('Save',['class'=>'btn btn-primary','type'=>"submit"])
        
                ];         
            }
        }else{
            /*
            *   Process for non-ajax request
            */
            if ($model->load($request->post()) && $model->save()) {
                return $this->redirect(['view', 'id' => $model->sid]);
            } else {
                return $this->render('create', [
                    'model' => $model,
                ]);
            }
        }
       
    }

    /**
     * Updates an existing Taozhuang model.
     * For ajax request will return json object
     * and for non-ajax request if update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $request = Yii::$app->request;
        $model = $this->findModel($id);       

        if($request->isAjax){
            /*
            *   Process for ajax request
            */
            Yii::$app->response->format = Response::FORMAT_JSON;
            if($request->isGet){
                return [
                    'title'=> "Update Taozhuang #".$id,
                    'content'=>$this->renderPartial('update', [
                        'model' => $this->findModel($id),
                    ]),
                    'footer'=> Html::button('Close',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"]).
                                Html::button('Save',['class'=>'btn btn-primary','type'=>"submit"])
                ];         
            }else if($model->load($request->post()) && $model->save()){
                return [
                    'forceReload'=>'true',
                    'title'=> "Taozhuang #".$id,
                    'content'=>$this->renderPartial('view', [
                        'model' => $this->findModel($id),
                    ]),
                    'footer'=> Html::button('Close',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"]).
                            Html::a('Edit',['update','id'=>$id],['class'=>'btn btn-primary','role'=>'modal-remote'])
                ];    
            }else{
                 return [
                    'title'=> "Update Taozhuang #".$id,
                    'content'=>$this->renderPartial('update', [
                        'model' => $this->findModel($id),
                    ]),
                    'footer'=> Html::button('Close',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"]).
                                Html::button('Save',['class'=>'btn btn-primary','type'=>"submit"])
                ];        
            }
        }else{
            /*
            *   Process for non-ajax request
            */
            if ($model->load($request->post()) && $model->save()) {
                return $this->redirect(['view', 'id' => $model->sid]);
            } else {
                return $this->render('update', [
                    'model' => $model,
                ]);
            }
        }
    }

    /**
     * Delete an existing Taozhuang model.
     * For ajax request will return json object
     * and for non-ajax request if deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $request = Yii::$app->request;
        $this->findModel($id)->delete();

        if($request->isAjax){
            /*
            *   Process for ajax request
            */
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ['forceClose'=>true,'forceReload'=>true];    
        }else{
            /*
            *   Process for non-ajax request
            */
            return $this->redirect(['index']);
        }


    }

     /**
     * Delete multiple existing Taozhuang model.
     * For ajax request will return json object
     * and for non-ajax request if deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionBulkDelete()
    {        
        $request = Yii::$app->request;
        $pks = $request->post('pks'); // Array or selected records primary keys
        foreach (Taozhuang::findAll(json_decode($pks)) as $model) {
            $model->delete();
        }
        

        if($request->isAjax){
            /*
            *   Process for ajax request
            */
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ['forceClose'=>true,'forceReload'=>true]; 
        }else{
            /*
            *   Process for non-ajax request
            */
            return $this->redirect(['index']);
        }
       
    }

    /**
     * Finds the Taozhuang model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Taozhuang the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Taozhuang::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    public function actionSelectTz($space_id)
    {
    	$model = new UploadForm();
    	$model->scenario = 'upload_img';
    	$this->layout = 'main_image';
    	$tz_space = GrpSpace::findAll(['useing'=>1,'id'=>$space_id]);
    	return $this->render('select_tz',[
    			'model' => $model,
    			'tz_space' => $tz_space,
    			]);

    }
    /**
     * 分页显示套装小图
     * @param unknown $pageNum
     * @param unknown $img_type
     */
    public function actionShowTzImage($page,$search,$tag,$pageSize=10,$tz_img_list)
    {
    
    	//$page = intval($_POST['pageNum']); //当前页
    	$where_type = " app_return=1 and space_id=".$search;
    	$where_name = " app_return=1 and name like '%".$search."%'";
    	if(!empty($tz_img_list)){
    		$where_type = " app_return=1 and space_id=".$search." and sid not in (".$tz_img_list.")";
    		$where_name = " app_return=1 and name like '%".$search."%' and sid not in (".$tz_img_list.")";
    	}
    	if($tag == 'type')
    		//$total = Image::find()->where(['type'=>$search])->count(); //总记录数
    		$total = Taozhuang::findBySql("select * from taozhuang where".$where_type)->count();
    	if($tag == 'name')
    		$total = Taozhuang::findBySql("select * from taozhuang where".$where_name)->count();
    
    	//$pageSize = 10; //每页显示数
    	$totalPage = ceil($total/$pageSize); //总页数
    
    	$startPage = $page*$pageSize;//开始记录
    	//构造数组
    
    	$arr['total'] = $total;
    	$arr['pageSize'] = $pageSize;
    	$arr['totalPage'] = $totalPage;
    	if($tag == 'type')
    		$result = Taozhuang::findBySql("select * from taozhuang where".$where_type." order by sid desc limit ". $startPage . "," . $pageSize )->all();
    	if($tag == 'name')
    		$result = Taozhuang::findBySql("select * from taozhuang where".$where_name." order by sid desc limit ". $startPage . "," . $pageSize )->all();
    
    	if($result !=null)
    	{
    		foreach ($result as $value )
    		{
    			$small_image = Image::findOne(['id'=>$value['img_small_id']]);
    			$arr['list'][] = array(
    					'sid' => $value['sid'],
    					'type' => $value['space_id'],
    					'name' => $value['name'],
    					'url' => $small_image['url'],//图片url
    					'width' => $small_image['width'],
    					'height' => $small_image['height'],
    
    			);
    		}
    		//var_dump($arr);
    		echo json_encode($arr); //输出JSON数据
    	}
    
    	else {
    		$arr['list'][] = array(
    				'sid' => '',
    				'space_id' => '',
    				'name' => '',
    				'url' => '',
    				'width' => '',
    				'height' => '');
    
    		echo json_encode($arr);
    	}
    
    
    }
    public function actionAddSidToBuildtype()
    {
    	  $type_id = $_GET['b_type_id'];
    	  $arr_tz=$_GET['arr_tz'];
    	 /*   $arr_tz=array("23");
    	  $type_id=1;  */   
    	if(!empty($arr_tz)){
    		$model = BuildType::findOne(['id'=>$type_id]);
    		$have_arr_tz_img_list = array();
    		if(!empty($model->tz_img_list)){
    			$have_arr_tz_img_list = explode(',', $model->tz_img_list);
    		}
    		foreach ($arr_tz as $value){
    			if(!in_array($value, $have_arr_tz_img_list))//如果新加的套装不在套装列表中
    			array_push($have_arr_tz_img_list, $value);
    		}
    		//重新排序 按照分类来
    		$all_space = GrpSpace::findAll(['useing'=>1]);
    		$arr_tz_small_img = array();
    		$count=count($have_arr_tz_img_list);
    		for($i=0;$i<$count;$i++){
    		    for($j=0;$j<count($all_space);$j++){
    		        for($z=0;$z<$count;$z++){
    		            if(!empty($have_arr_tz_img_list[$z])){
    		                $space_id=Taozhuang::get_space_id($have_arr_tz_img_list[$z]);
    		                if($space_id==$all_space[$j]['id']){
    		                    array_push($arr_tz_small_img, $have_arr_tz_img_list[$z]);
    		                   unset($have_arr_tz_img_list[$z]);
    		                    break;
    		                }
    		            }
    		        }
    		        
    		    }
    		}
    		$model->tz_img_list = implode(',', $arr_tz_small_img);
    		$model->save();
    	}
    	return 1;
    } 
    /*选择套装存入cookies*/
    public function actionWriteTzToCookie()
    {
    	var_dump($_GET['arr_tz']);//ajax传来数组
    	$arr_tz=$_GET['arr_tz'];
    	/*
    	$arr_tz_new = array();
    	foreach ($_GET as $k => $v){
    	if($k == 'arr_tz'){
    	array_push($arr_tz_new, $v);
    	}
    	}
    	var_dump($arr_tz_new);*/
    	$cookies = Yii::$app->response->cookies;
    	$cookies->add(new \yii\web\Cookie([
    			'name' => 'arr_tz',
    			'value' => $arr_tz,
    			]));
    
    	$cookies = Yii::$app->request->cookies;
    	if(isset($cookies['arr_tz']))
    	{
    	$tz_list = implode(',',$cookies['arr_tz']->value);
    	
    
    	}
    	return 1;
    }
	
	   /*更改pos*/
    public function actionUpdatePos($id)
    {
    	$request = Yii::$app->request;
    	$model = $this->findModel($id);
    	//$model_pos = TaozhuangPos::find()->where(['tzid'=>$id])->orderBy('pos ASC')->all();
    	//print_r($model_pos);return;
    	$sql="SELECT sys_image.url AS small_img,sys_item.id ,taozhuang_pos.*
                FROM taozhuang_pos
                LEFT JOIN sys_item on sys_item.id = taozhuang_pos.item_id 
                LEFT JOIN sys_image on sys_image.id = sys_item.img_small_id
                WHERE tzid=".$id." AND sys_item.id IN(SELECT taozhuang_pos.item_id FROM taozhuang_pos WHERE taozhuang_pos.tzid = ".$id.")
                ORDER BY taozhuang_pos.pos ASC";
        $model_pos = Taozhuang::findBySql($sql)->asArray()->all();
    	if($request->isAjax){
    		/*
    		 *   Process for ajax request
    		*/
    		Yii::$app->response->format = Response::FORMAT_JSON;
    		if($request->isGet){
    			return [
    			'title'=> $model->name."：".$model->tips,
    			'content'=>$this->renderPartial('update_pos', [
    					'model' => $this->findModel($id),
    					'model_pos' => $model_pos,//到页面
    					]),
    					'footer'=> Html::button('Close',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"])/*.
    					Html::button('保存',['class'=>'btn btn-primary','type'=>"submit"])*/
    					];
    		}else if($model->load($request->post()) && $model->save()){
    			return [
    			'forceReload'=>'true',
    			'title'=> "Taozhuang #".$id,
    			'content'=>$this->renderPartial('view', [
    					'model' => $this->findModel($id),
    					]),
    					'footer'=> Html::button('Close',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"])/*.
    					Html::a('Edit',['update_pos','id'=>$id],['class'=>'btn btn-primary','role'=>'modal-remote'])*/
    					];
    		}else{
    			return [
    			'title'=> "Update Taozhuang #".$id,
    			'content'=>$this->renderPartial('update_pos', [
    					'model' => $this->findModel($id),
    					]),
    					'footer'=> Html::button('Close',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"])/*.
    					Html::button('Save',['class'=>'btn btn-primary','type'=>"submit"])*/
    					];
    		}
    	}else{
    		/*
    		 *   Process for non-ajax request
    		*/
    		if ($model->load($request->post()) && $model->save()) {
    			return $this->redirect(['view', 'id' => $model->sid]);
    		} else {
    			return $this->render('update_pos', [
    					'model' => $model,
    					'model_pos' => $model_pos,
    					]);
    		}
    	}
    }
		    /**
     * 更改pos的item的销售状态
     * @param unknown $pos_id
     */
    public function actionTzposItemPay($item_id,$tzid,$pay_state){

    	if(TaozhuangPos::updateAll(['pay_state'=>$pay_state],['tzid'=>$tzid,'item_id'=>$item_id]))
    	{
    		return true;
    	}
    	return false;
   
    }
    //生成套装二维码
    public function actionGenerateQrcode(){
    	 
    	if(Yii::$app->request->isPost){
    		$sids = Yii::$app->request->post("sids");
    		if($sids){
    			foreach ($sids as $val){
    				Taozhuang::generateQRcode($val);
    			}
    		}
    		exit(json_encode(array('code'=>'1','msg'=>'已生成二维码')));
    	}
    }
   /**
    * 登录套装后台
    * @throws ForbiddenHttpException
    */
   public function actionEdit(){
   	
   		if(\Yii::$app->user->can('taozhuang-manage')){
   			$loginname = $login_id = Yii::$app->user->identity->username;
   			$timestamp = time();
   			$string = $loginname . $timestamp;
   			$string .= Yii::$app->user->identity->password_hash;
   			$string .= Yii::$app->user->identity->auth_key;
   			$key = md5($string);
			
   			$_arr = array(
   				"loginname={$loginname}",	
   				"key={$key}",
   				"timestamp={$timestamp}"
   			);
   			$param = implode('&amp;', $_arr);
			
   			$host = $_SERVER['SERVER_NAME'];
   			if($_SERVER['SERVER_PORT'] != '80'){
   				$host .= ":".$_SERVER['SERVER_PORT'];
   			}
   			$url = 'https://'.$host.self::BASE_URL.$param;
   			echo $url;
		   	return $this->render('edit', [
					'url'=> $url,
		   			]);
   		}else{
   			throw new ForbiddenHttpException(Yii::t('app','Sorry , You don\'t have permission'));
   		}
   } 
   /**
    * 修改生活方式
    * suiyue 2018/4/14
    */
   public function actionUpdateLifestyle($id){
	   	$model = $this->findModel($id);
   		if($model->load(Yii::$app->request->post())&&$model->save()){
   			return $this->redirect(['index']);
   		}else{
   			return $this->render('update_lifestyle', [
   					'model' => $model,
   			]);
   			
   		}
   }
   /**
    * (non-PHPdoc)
    * @see \yii\base\Controller::actions()
    * by suiyue
    */
   public function actions(){
   	return [
   			'upload'=>[
   					'class'=>'backend\widgets\ueditor\UEditorAction',
   					'config'=>[
   							//  /gjj/backend/web/images/
   								'imageUrlPrefix'=>"https://".$_SERVER['SERVER_NAME']."/gjj/backend/web/images/",//图片访问路径前缀
			   					'imagePathFormat'=>'{rand:2}/{time}{rand:6}',
			   				    'imageRoot'=>\Yii::getAlias("images")
   					]
   			]
   	];
   	
   }
   
}
